<template>
<div class="block">
  <div class="button__group">
    当前设备
    <el-select v-model="curentDevieId" placeholder="请选择">
      <el-option
        v-for="item in devices"
        :key="item.device_id"
        :label="item.device_name || item.device_mac"
        :value="item.device_id">
      </el-option>
    </el-select>
  </div>
  <div class="deviceStatus">
    设备状态：
    <span :class="isOnline ? 'online': 'offline'">{{isOnline ? '在线': '离线'}}</span>
  </div>

  <el-table
    class="mt30 table"
    :data="dataPoint"
    border>
    <el-table-column prop="index" label="索引" ></el-table-column>
    <el-table-column  label="端点值" prop="value"></el-table-column>
  </el-table>

  <div class="button__group">
    <el-button type="primary" @click="dialogFormVisible = true"  size="small" class="mt10">单个修改数据端点</el-button>
    <el-button type="primary" @click="dialogDeviceLogs = true"  size="small" class="mt10">发送透传</el-button>
  </div>
  
  
  <!-- 单个修改数据端点Form -->
  <el-dialog title="单个修改数据端点" :visible.sync="dialogFormVisible" size="full">
    <el-form :model="form" ref="form" :rules="rules" label-width="">
      <el-form-item label="index" prop="index">
        <el-input v-model="form.index" size="mini"></el-input>
      </el-form-item>

      <el-form-item label="value" prop="value">
        <el-input v-model="form.value" size="mini"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
      <el-button type="primary" @click="sendMessage" size="small">确 定</el-button>      
    </div>
  </el-dialog>

  <!-- 数据透传 -->
  <el-dialog title="数据透传" :visible.sync="dialogDeviceLogs" size="full">
    <el-form :model="pipeFrom" ref="pipeFrom" :rules="pipeFromrules" label-width="">
      <el-form-item label="pipeSync" prop="pipeSync">
        <el-input v-model="pipeFrom.pipeSync" size="mini" placeholder="以(255, 0, 2, 3, 5, 254)格式发送(0-255)"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
      <el-button type="primary" @click="sendPipe" size="small">确 定</el-button>      
    </div>
  </el-dialog>
</div>
</template>

<script>
import api from '@/api'
import _ from 'lodash'
import XSDK from 'static/xsdk'
export default {
  name: 'hello',

  data () {
    return {
      ws: null,
      dialogFormVisible: false,
      dialogDeviceLogs: false,
      curentDevieId: '',
      curentDevieSocket: {},
      isOnline: false,
      productId: '',
      vDevice: {},
      devices: [],
      devicesEvents: [],
      dataPoint: [],
      pipe: [],
      pipeFrom: {
        pipeSync: ''
      },
      pipeFromrules: {
        pipeSync: [
          { required: true, message: '请输入数据端点的值', trigger: 'blur' }
        ]
      },
      form: {
        index: '',
        value: '',
        type: ''
      },
      rules: {
        value: [
          { required: true, message: '请输入数据端点的值', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        index: [
          { required: true, message: '请输入数据端点的序号', trigger: 'blur' }
        ]
      },
      noSupportWebsocket: false
    }
  },

  computed: {
  },

  watch: {
    async curentDevieId (val) {
      if (!val) return
      this.dataPoint = []
      this.isOnline = false
      let find = _.find(this.devicesEvents, {id: val})
      if (!find) return
      await this.fetchVDevice(find.pid, find.id)
      console.log(this.vDevice)
      if (!this.vDevice.online) return
      if (this.vDevice.conn_prot === 1) {
        this.noSupportWebsocket = false
        this.curentDevieSocket = find
        this.fetchDatapoint(find)
        this.listenDatapoint(find)
        this.deviceStateChange(find)
      } else {
        this.noSupportWebsocket = true
        this.$message.error('当前协议，不支持websocket')
      }
    }
  },

  beforeDestroy () {
    this.destorySdk()
  },

  mounted () {
    this.init()
  },

  methods: {
    async init () {
      await this.fetchDeviceList()
      this.initWebsocket()
    },

    // 获取设备列表
    async fetchDeviceList () {
      let {data} = await api.fetchDeviceList(window.localStorage.userId)
      this.devices = data.map(item => {
        return {
          device_id: item.id,
          device_name: item.name,
          device_mac: item.mac,
          device_pid: item.product_id
        }
      })
      this.productId = this.devices && this.devices[0] && this.devices[0].device_pid
    },

    // 初始化维保socket
    initWebsocket () {
      let ws = new XSDK('websocket', {
        host: 'http://cm2.xlink.cn:23777',
        userid: window.localStorage.getItem('userId'), // 微信用户在云智易平台的user_id，通过获取OpenID接口获取
        authorize: window.localStorage.getItem('authorize'), // 微信用户在云智易平台的用户认证码，通过获取OpenID接口获取
        dp_version: 2 // 非必填，默认为1, 根据硬件的数据端点协议版本确定
      })
      this.ws = ws

      ws.on('ready', () => {
        ws.emit('adddevices',
          this.devices
        )
      })
      .on('devicesready', (devices) => {
        this.devicesEvents = devices
        if (!devices.length) return
        this.curentDevieId = devices[1].id
      })
      .on('error', (err) => {
        console.log(err)
      })
    },

    // 获取设备端点值
    fetchDatapoint (socketObj) {
      socketObj.emit('probe', (res) => {
        console.log(res)
        if (res.status === 0) {
          this.isOnline = true
        }
        if (res.data) {
          this.dataPoint = res.data.map(item => {
            return {
              index: item.index,
              value: item.value + ''
            }
          })
        }
      })
    },

    // 监听
    listenDatapoint (socketObj) {
      socketObj.on('data', (res) => {
        console.log(res)
        if (this.curentDevieId !== res.deviceId) return
        if (res.type === 'datapoint' && res.data.length) {
          let {data} = res
          console.log(data)
          this.updateDatapoint(data)
        }

        if (res.type === 'pipe_sync' && res.data.length) {
          let {data} = res
          console.log(data)
          this.pipe = data
          this.pipeFrom.pipeSync = data.join(',')
        }
        console.log('发生变化')
      })
    },

    // 更新数据端点
    updateDatapoint (data) {
      data.forEach(changData => {
        this.dataPoint.forEach((item, index) => {
          if (item.index === changData.index) {
            this.dataPoint.splice(index, 1, {
              index: changData.index,
              value: changData.value + ''
            })
          }
        })
      })
    },

    // 设备发生变化
    deviceStateChange (socketObj) {
      socketObj.on('statuschange', (status) => {
        console.log('deviceChange')
        this.isOnline = status === 1
      })
    },

    // 发送数据端点
    sendMessage () {
      if (!this.isOnline) {
        console.log('设备不在线')
        return
      }
      this.$refs.form.validate(valid => {
        if (!valid) return
        let val = this.form.value
        if (val === 'true' || val === 'false') {
          val = val === 'true'
        }
        let data = [{
          index: this.form.index * 1, // 必须整型
          value: val
        }]
        console.log(data)
        this.curentDevieSocket.emit('senddata', { // 发送数据端点数据
          type: 'datapoint',
          data
        }, (res) => {
          if (res.status === 0) {
            // 发送成功
            this.$message('发送成功')
            console.log('发送成功')
            this.updateDatapoint(data)
          }
        })
        this.dialogFormVisible = false
      })
    },

    // 发送透传
    sendPipe () {
      if (!this.isOnline || !this.pipeFrom.pipeSync) {
        console.log('设备不在线，或者透传为空')
        return
      }
      this.$refs.pipeFrom.validate(valid => {
        if (!valid) return
        let pipeSync = this.pipeFrom.pipeSync.split(',')
        console.log(pipeSync)
        // 透传FF 00 02 03 05 FE
        this.curentDevieSocket.emit('senddata', {
          type: 'pipe',
          data: pipeSync
        }, (res) => {
          if (res.status === 0) {
            // 发送成功
            console.log('发送成功')
            this.$message('发送成功')
            this.dialogDeviceLogs = false
          }
        })
      })
    },

    destorySdk () {
      if (this.ws) {
        this.ws.emit('destory')
        this.ws = null
        console.log('销毁socket')
      }
    },

    // 获取设备在线信息
    async fetchVDevice (productId, deviceId) {
      let {data} = await api.getVDevice(productId, deviceId)
      this.vDevice = data
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.block {
  width: 600px;
  height: calc(100% - 61px);
  box-sizing: border-box;
  padding: 10px;
  overflow: auto;
}
.table {
  width: 100%;
}
.mt30 {
  margin-top: 30px;
}
.mt10 {
  margin-top:10px; 
}
.button__group {
  padding:10px 0px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.online {
  color: green;
}
.offline {
  color: red;
}
</style>
